package com.music.note_android.ui.editor

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.music.note_android.data.model.Note
import com.music.note_android.data.repository.NoteRepository
import kotlinx.coroutines.launch
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

@HiltViewModel
class CanvasEditorViewModel @Inject constructor(
    private val noteRepository: NoteRepository
) : ViewModel() {

    private val _note = MutableLiveData<Note?>()
    val note: LiveData<Note?> = _note

    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading

    private val _error = MutableLiveData<String?>()
    val error: LiveData<String?> = _error

    private val _isSaved = MutableLiveData<Boolean>()
    val isSaved: LiveData<Boolean> = _isSaved

    private var hasUnsavedChanges = false
    private var canvasData: String? = null

    /**
     * 加载笔记
     */
    fun loadNote(noteId: String) {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                _error.value = null
                
                val note = noteRepository.getNoteById(noteId)
                _note.value = note
                
                // 加载画布数据
                canvasData = "" // TODO: 从dataPath加载画布数据
                hasUnsavedChanges = false
                
            } catch (e: Exception) {
                _error.value = "加载笔记失败: ${e.message}"
            } finally {
                _isLoading.value = false
            }
        }
    }

    /**
     * 保存画布数据
     */
    fun saveCanvas(noteId: String, newCanvasData: String) {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                _error.value = null
                
                // 更新笔记的画布数据
                val currentNote = _note.value
                if (currentNote != null) {
                    val updatedNote = currentNote.copy(
                        modifiedTime = System.currentTimeMillis()
                    )
                    
                    noteRepository.updateNote(updatedNote)
                    _note.value = updatedNote
                    
                    canvasData = newCanvasData
                    hasUnsavedChanges = false
                    _isSaved.value = true
                }
                
            } catch (e: Exception) {
                _error.value = "保存失败: ${e.message}"
            } finally {
                _isLoading.value = false
            }
        }
    }

    /**
     * 标记为已修改
     */
    fun markAsModified() {
        hasUnsavedChanges = true
    }

    /**
     * 检查是否有未保存的更改
     */
    fun hasUnsavedChanges(): Boolean {
        return hasUnsavedChanges
    }

    /**
     * 获取当前画布数据
     */
    fun getCanvasData(): String? {
        return canvasData
    }

    /**
     * 创建新的画布笔记
     */
    fun createNewCanvasNote(title: String, callback: (String) -> Unit) {
        viewModelScope.launch {
            try {
                val newNote = noteRepository.createNote(title)
                callback(newNote.id)
            } catch (e: Exception) {
                _error.value = "创建笔记失败: ${e.message}"
                callback("")
            }
        }
    }

    /**
     * 导出画布为图片
     */
    fun exportCanvasAsImage(canvasData: String, callback: (Boolean, String?) -> Unit) {
        viewModelScope.launch {
            try {
                // TODO: 实现画布导出为图片的逻辑
                // 这里需要将画布数据转换为Bitmap并保存到文件
                callback(true, "导出成功")
            } catch (e: Exception) {
                callback(false, "导出失败: ${e.message}")
            }
        }
    }

    /**
     * 导出画布为PDF
     */
    fun exportCanvasAsPdf(canvasData: String, callback: (Boolean, String?) -> Unit) {
        viewModelScope.launch {
            try {
                // TODO: 实现画布导出为PDF的逻辑
                callback(true, "导出成功")
            } catch (e: Exception) {
                callback(false, "导出失败: ${e.message}")
            }
        }
    }

    /**
     * 清除错误状态
     */
    fun clearError() {
        _error.value = null
    }

    /**
     * 清除保存状态
     */
    fun clearSavedState() {
        _isSaved.value = false
    }
}